from flask import Blueprint, request
from flask_jwt_extended import jwt_required, get_jwt_identity

from app.services.article_service import get_article_list_by_author, create_article_by_author, update_article_by_id, \
    delete_article_by_id
from app.utils.response import success, error

article_bp = Blueprint("articles", __name__, url_prefix="/articles")

"""
获取文章列表
"""
@article_bp.route('', methods=['GET'])
@jwt_required()
def get_article_list():
    author_id = get_jwt_identity()
    data = get_article_list_by_author(author_id)
    return success(data)

"""
新增文章
"""
@article_bp.route('', methods=['POST'])
@jwt_required()
def create_article():
    data = request.get_json()
    author_id = get_jwt_identity()
    data['author_id'] = author_id
    article = create_article_by_author(data)
    if article:
        return success(article)
    else:
        return error(msg='新增文章失败')

"""
修改文章
"""
@article_bp.route('/<int:id>', methods=['PUT'])
@jwt_required()
def update_article(id):
    data = request.get_json()
    data['id'] = id
    result = update_article_by_id(data)
    if result:
        return success(result)
    else:
        return error(msg='修改文章失败')

"""
删除文章
"""
@article_bp.route('/<int:id>', methods=['DELETE'])
@jwt_required()
def delete_article(id):
    result = delete_article_by_id(id)
    if result:
        return success()
    else:
        return error(msg='删除文章失败')
